<!DOCTYPE html>
<html>
<head>
    <title>小工具</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./webjars/bootstrap/4.5.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/common.css">
    <script src="./webjars/jquery/3.4.1/jquery.min.js"></script>
    <script src="./webjars/popper.js/1.16.0/popper.min.js"></script>
    <script src="./webjars/bootstrap/4.5.3/js/bootstrap.min.js"></script>
    <script src="./webjars/layer/dist/layer.js"></script>
    <link rel="icon" href="./img/favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="./img/favicon.ico" type="image/x-icon"/>
    <style>
        .custom-file-input:lang(zh) ~ .custom-file-label::after {
            content: "浏览";
        }

        .custom-file-label::after {
            content: "浏览";
        }
    </style>
</head>
<body>
<div id="head">
</div>
<script>
    $("#head").load("./head.html", function () {
        $("#index").addClass("active");
    });
</script>
<form class="container-fluid row mt-5" style="display: flex;flex-direction: column;  align-items: center;"
      id="postForm">
    <div class="col-5 mt-5" style="display: flex;flex-direction: column;min-width: 400px;">
        <div class="mb-3">
            <div class="custom-control-inline">支持的格式:</div>
            <div id="supportFormat" class="custom-control-inline"> png</div>
        </div>
        <div class="mb-3 custom-control-inline form-group" style="display: flex;align-items: center">
            <label for="size" style="width: 100px;">图标大小:</label>
            <select class="form-control" id="size">
                <option value="16">16*16</option>
                <option value="32">32*32</option>
                <option value="64">64*64</option>
                <option value="128" selected>128*128</option>
                <option value="256">256*256</option>
                <option value="512">512*512</option>
                <option value="1024">1024*1024</option>
            </select>
        </div>
        <div class="custom-file mb-3 form-group">
            <input type="file" class="custom-file-input" id="customFile" name="filename"
                   onchange="showFilename(this.files[0])">
            <label class="custom-file-label" for="customFile" id="fileLabel">选择文件</label>
        </div>

        <div class="btn-group" style="display: flex;justify-content: flex-end;">
            <button type="button" class="btn btn-custom-end" id="sendBtn">转换并下载</button>
        </div>
    </div>
    <img id="img" style="width: 100px;height: 100px;">
</form>

</body>
<script>
    function showFilename(file) {
        $("#fileLabel").html(file.name);
    }

    // canvas转dataURL：canvas对象、转换格式、图像品质
    function canvasToDataURL(canvas, format, quality) {
        return canvas.toDataURL(format || 'image/jpeg', quality || 1.0);
    }

    // image转canvas：图片地址
    function imageToCanvas(src, cb) {
        const canvas = document.createElement('CANVAS');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        img.src = src;
        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            cb(canvas);
        };
    }

    // image转dataURL
    function imageToDataURL(src, cb) {
        imageToCanvas(src, function (canvas) {
            cb(canvasToDataURL(canvas));
        });
    }

    $(document).ready(function () {
        $.ajax({
            url: "/support-formats",
            type: "GET",
            success: function (data, status) {
                if (status === 'success') {
                    $("#supportFormat").text(data.data.toString())
                } else {
                    alert("error")
                }
            }
        });

        $("#sendBtn").click(function () {
            const size = $("#size").val();
            if (!size) {
                return;
            }
            console.log(size)

            const file = $("#customFile")[0].files[0];
            if (!file) {
                return;
            }
            const fd = new FormData();
            //由于后台接收的数据只能是序列化之后的样子，所以将第一个表单的字段存放在cookie中。通过fd.append()以键值对形式存放
            fd.append(file.name, file);
            fd.append("size", size);

            const layerIndex = layer.load(2);
            $.ajax({
                url: "/image2icoBase64",
                async: false,
                type: "POST",
                processData: false,//因为data值是FormData对象，不需要对数据做处理。
                contentType: false,//因为是由<form>表单构造的FormData对象，所以这里设置为false。
                data: fd,
                success: function (data, status, xhr) {
                    layer.close(layerIndex);
                    const fileName = xhr.getResponseHeader("Content-Disposition").split(";")[1].substring(10)
                    //const type = xhr.getResponseHeader("Content-Type")
                    if (status === 'success') {
                        console.log(data.length)
                        let imageData = "data:image/x-icon;base64," + data;
                        $("#img").attr("src", imageData)
                        imageToDataURL(imageData, function (url) {
                            const a = document.createElement('a');
                            a.download = fileName;
                            a.href = url
                            a.click()
                        })
                    } else {
                        alert("error")
                    }
                }, error: function () {
                    layer.close(layerIndex);
                    alert("error")
                }
            })
        })
    })
</script>
</html>
